<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"llmysnow.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="介绍 Node 事件循环与浏览器事件循环的区别，以及 Node 多线程">
<meta property="og:type" content="article">
<meta property="og:title" content="Node 事件循环及多线程">
<meta property="og:url" content="http://llmysnow.top/posts/126e4b0f/index.html">
<meta property="og:site_name" content="奇幻的梦之旅">
<meta property="og:description" content="介绍 Node 事件循环与浏览器事件循环的区别，以及 Node 多线程">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/%E6%B5%8F%E8%A7%88%E5%99%A8EventLoop.gif">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/NodeEventLoop.png">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/NodeEvent6.png">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/cpu1.png">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/cpu3.png">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/clusterWorker.png">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/%E6%83%8A%E7%BE%A4%E7%8E%B0%E8%B1%A1.png">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/cluster%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1.png">
<meta property="article:published_time" content="2022-04-23T11:27:04.395Z">
<meta property="article:modified_time" content="2022-04-23T11:27:47.146Z">
<meta property="article:author" content="LiLyn">
<meta property="article:tag" content="Node">
<meta property="article:tag" content="浏览器">
<meta property="article:tag" content="事件循环">
<meta property="article:tag" content="多线程">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/%E6%B5%8F%E8%A7%88%E5%99%A8EventLoop.gif">

<link rel="canonical" href="http://llmysnow.top/posts/126e4b0f/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Node 事件循环及多线程 | 奇幻的梦之旅</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="奇幻的梦之旅" type="application/atom+xml">
</head>
<!--即时预加载技术，在用户点击之前预先加载页面-->
<script src="https://cdn.jsdelivr.net/gh/TRHX/CDN-for-itrhx.com@2.0.2/js/instantclick-1.2.2.js" type="module"></script>
<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
	  <!--<a target="_blank" rel="noopener" href="https://github.com/llwodexue" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>-->
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">奇幻的梦之旅</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">http://llmysnow.top/</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://llmysnow.top/posts/126e4b0f/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/logo.jpg">
      <meta itemprop="name" content="LiLyn">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="奇幻的梦之旅">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Node 事件循环及多线程
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-04-23 19:27:04" itemprop="dateCreated datePublished" datetime="2022-04-23T19:27:04+08:00">2022-04-23</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>20k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>19 分钟</span>
            </span>
            <div class="post-description">介绍 Node 事件循环与浏览器事件循环的区别，以及 Node 多线程</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="浏览器事件循环"><a href="#浏览器事件循环" class="headerlink" title="浏览器事件循环"></a>浏览器事件循环</h2><blockquote>
<p><a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1nK4y1M73T?spm_id_from=333.999.0.0">前端必会的异步编程 微任务 宏任务 Node.js 事件循环与多进程</a></p>
<p>推荐结合：<a target="_blank" rel="noopener" href="https://nodejs.org/zh-cn/docs/guides/event-loop-timers-and-nexttick/">Node 官方文档</a> 查漏补缺或解决疑问</p>
</blockquote>
<p><strong>JS 为什么是单线程的</strong></p>
<p>浏览器 JS 的作用是操作 DOM，这决定了它只能是单线程的，否则会带来很多复杂的问题</p>
<ul>
<li>比如：假定 JavaScript 同时又两个线程，一个线程在某个 DOM 节点上添加内容，另一个线程删除了这个节点，这时浏览器应该以哪个线程为准？</li>
</ul>
<p><strong>浏览器是多线程</strong></p>
<p>浏览器基于 EventQueue 事件队列、EventLoop 事件循环两大机制，构建出 “异步编程的效果” -&gt; 单线程异步操作</p>
<ul>
<li>GUI 渲染线程</li>
<li>JS 引擎线程【渲染解析 JS 的】</li>
<li>DOM/定时器监听等线程</li>
<li>HTTP 网络线程</li>
</ul>
<p><strong>浏览器中的 Event Loop</strong></p>
<ul>
<li>主线程从任务队列中读取事件，这个过程是循环不断的，这种整个运行机制又称为 <code>Event Loop</code> （事件循环）</li>
<li>执行栈在执行完 <strong>同步任务</strong> 后，查看 <strong>执行栈</strong> 是否为空，如果 <strong>执行栈</strong> 为空，就回去检查 <strong>微任务</strong> 队列是否为空，如果为空的话，就会执行 <strong>宏任务</strong>，否则就一次性执行完所有 <strong>微任务</strong></li>
</ul>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/js-img/%E6%B5%8F%E8%A7%88%E5%99%A8EventLoop.gif"></p>
<p><strong>事件队列分为同步任务（synchronous）和异步任务（asynchronous）</strong></p>
<ol>
<li>所有同步任务都在主线程上执行，形成了一个执行栈（execution content stack）</li>
<li>主线程之外，还存在一个 “任务队列” （task queue），只要异步任务有了运行结果，就在 “任务队列” 之中放置一个事件</li>
<li>一旦 “执行栈” 中的所有同步任务执行完毕，系统就会读取 “任务队列”，看看里面有哪些事件，哪些对应的异步任务，于是等任务结束状态，进入执行栈，开始执行</li>
<li>主线程不断重复上面的第三步</li>
</ol>
<p><strong>除了广义的同步任务和异步任务，异步任务可以细分为宏任务（macrotask）和微任务（microtask）</strong></p>
<ul>
<li><p>宏任务</p>
<p>UI rendering 是浏览器的宏任务</p>
</li>
</ul>
<table>
<thead>
<tr>
<th></th>
<th>浏览器</th>
<th>Node</th>
</tr>
</thead>
<tbody><tr>
<td><code>I/O</code></td>
<td>✔️</td>
<td>✔️</td>
</tr>
<tr>
<td><code>setTimeout</code></td>
<td>✔️</td>
<td>✔️</td>
</tr>
<tr>
<td><code>setInterval</code></td>
<td>✔️</td>
<td>✔️</td>
</tr>
<tr>
<td><code>setImmediate</code></td>
<td>❌</td>
<td>✔️</td>
</tr>
<tr>
<td><code>requestAnimationFrame</code></td>
<td>✔️</td>
<td>❌</td>
</tr>
</tbody></table>
<ul>
<li>微任务</li>
</ul>
<table>
<thead>
<tr>
<th></th>
<th>浏览器</th>
<th>Node</th>
</tr>
</thead>
<tbody><tr>
<td><code>process.nextTick</code></td>
<td>❌</td>
<td>✔️</td>
</tr>
<tr>
<td><a target="_blank" rel="noopener" href="http://javascript.ruanyifeng.com/dom/mutationobserver.html"><code>MutationObserver</code></a></td>
<td>✔️</td>
<td>❌</td>
</tr>
<tr>
<td><code>Promise.then catch finally</code></td>
<td>✔️</td>
<td>✔️</td>
</tr>
</tbody></table>
<ul>
<li>练习：</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;setTimeout&#x27;</span>)</span><br><span class="line">&#125;, <span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">Promise</span>.resolve().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;promise1&#x27;</span>)</span><br><span class="line">  <span class="built_in">Promise</span>.resolve().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;promise2&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// promise1 promise2 setTimeout</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* ---------- */</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">Promise</span>.resolve().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;promise&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;, <span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">Promise</span>.resolve().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;setTimeout&#x27;</span>)</span><br><span class="line">  &#125;, <span class="number">0</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;main&#x27;</span>)</span><br><span class="line"><span class="comment">// main promise setTimeout</span></span><br></pre></td></tr></table></figure>

<h2 id="Node-js-事件循环"><a href="#Node-js-事件循环" class="headerlink" title="Node.js 事件循环"></a>Node.js 事件循环</h2><p>Node 的 Event Loop 是基于 <code>libuv</code> 实现的，<code>libuv</code> 使用异步、事件驱动的编程方法，核心是提供 <code>I/O</code> 的事件循环和异步回调</p>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/js-img/NodeEventLoop.png"></p>
<h3 id="事件循环六个阶段"><a href="#事件循环六个阶段" class="headerlink" title="事件循环六个阶段"></a>事件循环六个阶段</h3><blockquote>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903764202094606#heading-28">一次弄懂Event Loop（彻底解决此类面试问题）</a></p>
<p><a target="_blank" rel="noopener" href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/">The Node.js Event Loop</a></p>
</blockquote>
<p>Node 的 Event Loop 是基于 <code>libuv</code> 实现的，<code>libuv</code> 使用异步、事件驱动的编程方法，核心是提供 <code>I/O</code> 的事件循环和异步回调</p>
<p>当 Node.js 启动时会初始化 Event Loop，每一个 Event Loop 都会包含如下六个循环阶段：</p>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/js-img/NodeEvent6.png"></p>
<p><strong>阶段概览</strong></p>
<ol>
<li><p><strong>timers（定时器）</strong>：此阶段执行那些由 <code>setTimeout()</code> 和 <code>setInterval()</code> 调度的回调函数</p>
</li>
<li><p><strong>pending callbacks</strong>：执行 I/O 回调，此阶段执行几乎所有的回调函数，除了 <strong>close callbacks（关闭回调）</strong> 和那些由 <strong>timers</strong> 与 <code>setImmediate()</code> 调度的回调</p>
<p><code>setImmediate() ≈ setTimeout(cb, 0)</code></p>
</li>
<li><p>idle（空转），prepare：此阶段只在内部使用</p>
</li>
<li><p><strong>poll（轮询）</strong>：检索新的 I/O 事件，在恰当的时候 Node 会阻塞这个阶段</p>
</li>
<li><p>check（检查）：<code>setImmediate()</code> 设置的回调会在这个阶段被调用</p>
</li>
<li><p>close callbacks（关闭事件的回调）：诸如：<code>http.server.on(&#39;close&#39;, [fn])</code>、<code>socket,on(&#39;close&#39;, [fn])</code>，此类的回调会在此阶段被调用</p>
</li>
</ol>
<p><strong>poll 阶段</strong></p>
<p>如果 Event Loop 进入了 <strong>poll</strong> 阶段，且代码未设定 <code>timer</code>，将会发生下面情况：</p>
<ul>
<li>如果 <code>poll</code> 队列不为空，则 Event Loop 将 <strong>同步执行</strong> <code>callback</code> 队列，直至队列为空或者达到系统上限</li>
<li>如果 <code>poll</code> 队列为空，将会发生下面情况：<ul>
<li>如果有 <code>setImmediate()</code> 回调需要执行， Event Loop 会立即停止执行 <strong>poll</strong> 阶段并执行 <strong>check</strong> 阶段，然后执行回调</li>
<li>如果没有 <code>setImmediate()</code> 回调需要执行，Event Loop 将阻塞在 <strong>poll</strong> 阶段，等待 <code>callback</code> 被添加到任务队列中，然后执行</li>
</ul>
</li>
</ul>
<p>如果 Event Loop 进入了 <strong>poll</strong> 阶段，且代码设定了 <code>timer</code>：</p>
<ul>
<li>如果 <code>poll</code> 队列为空，则 Event Loop 将检查 <code>timer</code> 是否超时，如果有的话会回到 <strong>timers</strong> 阶段执行回调</li>
</ul>
<p><strong>不同版本 Node</strong></p>
<ul>
<li>浏览器只要执行了一个宏任务就会执行微任务队列</li>
<li>Node 10(11以下) 中只有全部执行了 <strong>timers</strong> 阶段队列的全部任务才执行微任务队列</li>
<li>Node 11 在 <strong>timers</strong> 阶段的 <code>setTimeout()</code>、<code>setInterval()</code> 和在 <strong>check</strong> 阶段的 <code>setImmediate()</code> 修改为一旦执行一个阶段里的一个任务就会执行微任务队列</li>
</ul>
<h3 id="fs-和-setTimeout-的关系"><a href="#fs-和-setTimeout-的关系" class="headerlink" title="fs 和 setTimeout 的关系"></a>fs 和 setTimeout 的关系</h3><ol>
<li>执行 <code>setTimeout(fn, 10)</code>，会立即执行 Node 六个阶段，当前时间为 0ms， <strong>timers</strong> 阶段没有任何 <code>callback</code> 加入，跳过</li>
<li>执行 <strong>pending callbacks</strong> 阶段，执行定时器或 <code>setImmediate</code> 以外的回调，没有跳过</li>
<li>执行 <strong>poll</strong> 阶段，<code>poll</code> 队列为空且没有 <code>setImmediate()</code> ，会阻塞等待 2ms，等待 <code>fs.readfile</code> 读取文件完毕执行其回调，会调阻塞代码 20ms</li>
<li>此时时间为 22ms，<code>poll</code> 队列为空且有设定的 <code>timer</code>，因为 <code>setTimeout</code> 的回调执行 10ms，此时时间已经达到，事件循环会进入 <strong>timers</strong> 阶段，执行 <code>setTimeout(fn, 10)</code></li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">someAsyncOperation</span>(<span class="params">callback</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 花费2ms</span></span><br><span class="line">  fs.readFile(path.resolve(__dirname, <span class="string">&#x27;/read.txt&#x27;</span>), callback)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> timeoutScheduled = <span class="built_in">Date</span>.now()</span><br><span class="line"><span class="keyword">let</span> fileReadTime = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> delay = <span class="built_in">Date</span>.now() - timeoutScheduled</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`setTimeout: <span class="subst">$&#123;delay&#125;</span> ms have passed since I was scheduled`</span>)</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`fileReaderTime <span class="subst">$&#123;fileReadTime - timeoutScheduled&#125;</span>`</span>)</span><br><span class="line">&#125;, <span class="number">10</span>)</span><br><span class="line"></span><br><span class="line">someAsyncOperation(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  fileReadTime = <span class="built_in">Date</span>.now()</span><br><span class="line">  <span class="keyword">while</span> (<span class="built_in">Date</span>.now() - fileReadTime &lt; <span class="number">20</span>) &#123;&#125; <span class="comment">// 卡住20ms</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">setTimeout: 22 ms have passed since I was scheduled</span></span><br><span class="line"><span class="comment">fileReaderTime 2</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>稍微做下改变，假设文件读取花费了 9ms，定时器只花了 5ms</p>
<ol>
<li>执行 <code>setTimeout(fn, 5)</code>，当前时间为 0ms， <strong>timers</strong> 阶段没有任何 <code>callback</code> 加入，跳过</li>
<li>执行 <strong>pending callbacks</strong> 阶段，执行定时器或 <code>setImmediate</code> 以外的回调，没有跳过</li>
<li>执行 <strong>poll</strong> 阶段，<code>poll</code> 队列为空且没有 <code>setImmediate()</code> ，会阻塞等待 5ms，当前时间为 5ms，此时 <code>poll</code> 队列为空且设定了 <code>timer</code>，事件循环会进入 <strong>timers</strong> 阶段，执行<code>setTimeout(fn, 5)</code> </li>
<li>重新执行阶段，走到 <strong>poll</strong> 阶段，继续阻塞，当前时间等待到 9ms，执行 <code>fs.readFile</code></li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">someAsyncOperation</span>(<span class="params">callback</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 花费9ms</span></span><br><span class="line">  fs.readFile(path.resolve(__dirname, <span class="string">&#x27;/read.txt&#x27;</span>), callback)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> timeoutScheduled = <span class="built_in">Date</span>.now()</span><br><span class="line"><span class="keyword">let</span> fileReadTime = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> delay = <span class="built_in">Date</span>.now() - timeoutScheduled</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`setTimeout: <span class="subst">$&#123;delay&#125;</span> ms have passed since I was scheduled`</span>)</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`fileReaderTime <span class="subst">$&#123;fileReadTime - timeoutScheduled&#125;</span>`</span>)</span><br><span class="line">&#125;, <span class="number">5</span>)</span><br><span class="line"></span><br><span class="line">someAsyncOperation(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  fileReadTime = <span class="built_in">Date</span>.now()</span><br><span class="line">  <span class="keyword">while</span> (<span class="built_in">Date</span>.now() - fileReadTime &lt; <span class="number">20</span>) &#123;&#125; <span class="comment">// 卡住20ms</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">setTimeout: 5 ms have passed since I was scheduled</span></span><br><span class="line"><span class="comment">fileReaderTime 9</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h3 id="setTimeout-和-setImmediate"><a href="#setTimeout-和-setImmediate" class="headerlink" title="setTimeout 和 setImmediate"></a>setTimeout 和 setImmediate</h3><blockquote>
<p>在 Node.js 中，<code>setTimeout(fn, 0) === setTimeout(fn, 1)</code></p>
<p>在浏览器里，<code>setTimeout(fn, 0) === setTimeout(fn, 4)</code></p>
</blockquote>
<p>setTimeout  和 setImmediate 执行顺序不确定</p>
<ul>
<li>因为事件循环启动也是需要时间的，可能执行 <strong>poll</strong> 阶段已经超过了 1ms，此时 <code>setTimeout</code> 会先执行，反之 <code>setImmediate</code>  先执行</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">setImmediate(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;setImmediate&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;setTimeout&#x27;</span>)</span><br><span class="line">&#125;, <span class="number">0</span>)</span><br><span class="line"><span class="comment">// 一次 setImmediate setTimeout</span></span><br><span class="line"><span class="comment">// 一次 setTimeout setImmediate</span></span><br></pre></td></tr></table></figure>

<p>setTimeout  和 setImmediate 执行顺序是确定的</p>
<ul>
<li><p>一开始 <code>poll</code> 队列为空，没有设定 <code>setImmediate </code>，代码会进行阻塞，执行 <code>fs.readFile</code>，2ms 后读取文件完毕，执行其回调</p>
</li>
<li><p><code>poll</code> 队列为空，且设定了 <code>setImmediate </code> ，结束 <strong>poll</strong> 阶段进入 <strong>check</strong> 阶段，<strong>check</strong> 阶段会执行 <code>setImmediate </code>，此时会执行 <code>setImmediate</code></p>
<p>即使 <code>setTimeout</code> 和 <code>setImmediate</code> 替换位置也是 <code>setImmediate</code> 先执行</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>)</span><br><span class="line"></span><br><span class="line">fs.readFile(path.resolve(__dirname, <span class="string">&#x27;/read.txt&#x27;</span>), <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  setImmediate(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;setImmediate&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;setTimeout&#x27;</span>)</span><br><span class="line">  &#125;, <span class="number">0</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// setImmediate setTimeout</span></span><br></pre></td></tr></table></figure>

<h3 id="process-nextTick"><a href="#process-nextTick" class="headerlink" title="process.nextTick"></a>process.nextTick</h3><p><strong>process.nextTick() 不在 Event Loop 的任何阶段执行，而是在各个阶段切换的中间执行</strong>，即从一个阶段切换到下个阶段前执行</p>
<ol>
<li>执行 <code>fs.readFile</code>，首先 <code>setTimeout</code>、<code>setImmediate</code> 放进 I/O 里，此时有 <code>setImmediate()</code> 回调需要执行，事件循环立即结束 <strong>poll</strong> 阶段并执行 <strong>check</strong> 阶段，执行 <code>nextTick()</code> ，然后执行回调</li>
<li><strong>check</strong> 阶段之后会到第二个事件循环的 <strong>timer</strong> 阶段，执行 <code>nextTick()</code> ，再执行 <code>setTimeout</code> 回调</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>)</span><br><span class="line"></span><br><span class="line">fs.readFile(path.resolve(__dirname, <span class="string">&#x27;/read.txt&#x27;</span>), <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;setTimeout&#x27;</span>)</span><br><span class="line">  &#125;, <span class="number">0</span>)</span><br><span class="line"></span><br><span class="line">  setImmediate(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;setImmediate&#x27;</span>)</span><br><span class="line">    process.nextTick(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&#x27;nextTick3&#x27;</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  process.nextTick(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;nextTick1&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  process.nextTick(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;nextTick2&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="nextTick-应用场景"><a href="#nextTick-应用场景" class="headerlink" title="nextTick 应用场景"></a>nextTick 应用场景</h3><ol>
<li><p>在多个事件里交叉执行 CPU 运算密集型的任务：</p>
<p>在这种模式下，我们不需要递归的调用 <code>compute()</code>，我们只需要在事件循环中使用 <code>process.nextTick()</code> 定义 <code>compute()</code> 在下一个时间点执行即可。在这个过程中，如果有新的 http 请求进来，事件循环机制会先处理新的请求，然后再调用 <code>computed()</code>。反之，如果你把 <code>compute()</code> 放在一个递归调用里，那系统就会一直阻塞在 <code>computed()</code> 里，无法处理新的 http 请求了</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">compute</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  process.nextTick(compute)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">http</span><br><span class="line">  .createServer(<span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">    res.writeHead(<span class="number">200</span>, &#123; <span class="string">&#x27;Content-Type&#x27;</span>: <span class="string">&#x27;text/plain&#x27;</span> &#125;)</span><br><span class="line">    res.end(<span class="string">&#x27;hello world&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">  .listen(<span class="number">5000</span>, <span class="string">&#x27;127.0.0.1&#x27;</span>)</span><br><span class="line"></span><br><span class="line">compute()</span><br></pre></td></tr></table></figure>
</li>
<li><p>保持回调函数异步执行的原则</p>
<p>当你给一个函数定义一个回调函数时，你要确保这个回调是被异步执行的。下面这个例子中的回调函数违反了这个原则：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">asyncFake</span>(<span class="params">data, callback</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (data === <span class="string">&#x27;foo&#x27;</span>) callback(<span class="literal">true</span>)</span><br><span class="line">  <span class="keyword">else</span> callback(<span class="literal">false</span>)</span><br><span class="line">&#125;</span><br><span class="line">asyncFake(<span class="string">&#x27;bar&#x27;</span>, <span class="function"><span class="params">result</span> =&gt;</span> &#123;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> client = net.connect(<span class="number">8124</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;client connected&#x27;</span>)</span><br><span class="line">  client.write(<span class="string">&#x27;hello world\r\n&#x27;</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>如果是因为某种原因，<code>net.connect()</code> 变成同步执行的了，回调函数就会被立即执行，因此回调函数写到客户端的变量就永远不会被初始化了</p>
<p>这种情况下我们就可以使用 <code>process.nextTick()</code> 把上面 <code>asyncFake()</code> 改成异步执行的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">asyncReal</span>(<span class="params">data, callback</span>) </span>&#123;</span><br><span class="line">  process.nextTick(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    callback(data === <span class="string">&#x27;foo&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>用在事件触发过程中</p>
<p>EventEmitter 有 2 个比较核心的方法，on 和 emit。node 自带发布/订阅模式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> EventEmitter = <span class="built_in">require</span>(<span class="string">&#x27;events&#x27;</span>).EventEmitter</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">App</span> <span class="keyword">extends</span> <span class="title">EventEmitter</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> App()</span><br><span class="line">app.on(<span class="string">&#x27;start&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;start&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.emit(<span class="string">&#x27;start&#x27;</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;111&#x27;</span>) <span class="comment">// emit是同步的方法</span></span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">start</span></span><br><span class="line"><span class="comment">111</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> EventEmitter = <span class="built_in">require</span>(<span class="string">&#x27;events&#x27;</span>).EventEmitter</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">StreamLibrary</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> self = <span class="built_in">this</span></span><br><span class="line"></span><br><span class="line">  process.nextTick(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    self.emit(<span class="string">&#x27;start&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line">StreamLibrary.prototype.__proto__ = EventEmitter.prototype</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> stream = <span class="keyword">new</span> StreamLibrary()</span><br><span class="line"><span class="comment">// 保证订阅在发布之前</span></span><br><span class="line">stream.on(<span class="string">&#x27;start&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;Reading has started&#x27;</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="Node-多线程"><a href="#Node-多线程" class="headerlink" title="Node 多线程"></a>Node 多线程</h2><h3 id="多进程和多线程"><a href="#多进程和多线程" class="headerlink" title="多进程和多线程"></a>多进程和多线程</h3><p><strong>为什么需要多进程</strong></p>
<ul>
<li>Node.js 单线程，在处理 http 请求的时候一个错误都会导致整个进程的退出，这是灾难级的</li>
</ul>
<p><strong>线程和进程</strong></p>
<ul>
<li>进程是资源分配的最小单位，线程是 CPU 调度的最小单位</li>
<li>“进程” —— 资源分配的最小单位</li>
<li>“线程” —— 程序执行的最小单位</li>
</ul>
<p><strong>线程是进程的一个执行流</strong>，是 CPU 调度和分派的基本单位，它是比进程更小的能独立运行的基本单位。<strong>一个进程由几个线程组成</strong>，线程与同属一个进程的其它线程共享进程拥有的全部资源（一个进程下的线程可以去通信的、共享资源）</p>
<p><strong>进程有独立的地址空间</strong>，一个进程崩溃后，在保护模式下不会对其它进程产生影响，而线程只是一个进程中的不同执行路径，线程有自己的堆栈和局部变量，但是线程没有单独的地址空间，<strong>一个线程死掉就等于整个进程死掉</strong></p>
<p>举例：谷歌浏览器</p>
<ul>
<li>进程：一个 Tab 页就是一个进程</li>
<li>线程：一个 Tab 页又有多个线程组成、渲染线程、JS 执行线程、垃圾回收、service worker 等等</li>
</ul>
<p>举例：Node 服务</p>
<ul>
<li>ab 是 apache 自带的压力测试工具 <code>ab -n1000 -c20 &#39;192.168.31.25:8000/&#39;</code></li>
<li>进程：监听某一个端口的 http 服务</li>
<li>线程：http 服务由多个线程组成，比如：<ul>
<li>主线程：获取代码、编译执行</li>
<li>编译进程：主线程执行的时候，可以优化代码</li>
<li>Profiler 线程：记录哪些方法耗时，为优化提供支持</li>
<li>其他线程：用于垃圾回收清理工作，因为是多个线程，所以可以并行清除</li>
</ul>
</li>
</ul>
<h3 id="如何选选择多进程还是多线程"><a href="#如何选选择多进程还是多线程" class="headerlink" title="如何选选择多进程还是多线程"></a>如何选选择多进程还是多线程</h3><ul>
<li>多进程还是多线程一般是结合起来使用，千万不要陷入非此即彼的误区</li>
</ul>
<table>
<thead>
<tr>
<th>对比维度</th>
<th>多进程</th>
<th>多线程</th>
<th>总结</th>
</tr>
</thead>
<tbody><tr>
<td>数据共享、同步</td>
<td>数据共享复杂，需要用IPC：数据是分开的，同步简单</td>
<td>因为共享进程数据，数据共享简单，但也是因为这个原因导致同步复杂</td>
<td>各有优势</td>
</tr>
<tr>
<td>内存、CPU</td>
<td>占用内存多，切换复杂，CPU利用率低</td>
<td>占用内存少，切换简单，CPU利用率高</td>
<td>线程占优</td>
</tr>
<tr>
<td>创建销毁、切换</td>
<td>创建销毁、切换复杂，速度慢</td>
<td>创建销毁、切换简单，速度很快</td>
<td>线程占优</td>
</tr>
<tr>
<td>编程、调试</td>
<td>编程简单、调试简单</td>
<td>编程复杂、调试复杂</td>
<td>进程占优</td>
</tr>
<tr>
<td>可靠性</td>
<td>进程间不会互相影响</td>
<td>一个线程挂掉会导致整个进程挂掉</td>
<td>进程占优</td>
</tr>
<tr>
<td>分布式</td>
<td>适应于多核、多机分布式：如果一台机器不够，扩展到多台机器比较简单</td>
<td>适应于多核分布式</td>
<td>进程占优</td>
</tr>
</tbody></table>
<ol>
<li><p><strong>需要频繁创建销毁的优先使用线程</strong></p>
<p>这种原则最常见的应用就是 Web 服务器了，来一个连接建立一个线程，断了就销毁线程，要是用进程，创建和销毁的代价是很难承受的</p>
</li>
<li><p><strong>需要进行大量计算的优先使用线程</strong></p>
<p>所谓大量计算，当然就是耗费很多 CPU，切换频繁了，这种情况下线程是最合适的</p>
<p>这种原则最常见的是图像处理、算法处理</p>
</li>
<li><p><strong>强相关的处理使用线程，弱相关的处理使用进程</strong></p>
<p>JS 和 DOM 强相关</p>
<p>浏览器两个窗口弱相关</p>
<p>一般的 Server 需要完成如下任务：消息收发、消息处理。”消息收发” 和 “消息处理” 就是弱相关任务，而 “消息处理” 里面可能又分为 “消息解码”、”业务处理”，这两个任务相对于来说相关性就要强多了，因此 “消息收发” 和 “消息处理” 可以分进程设计，”消息解码”、”业务处理” 可以分线程设计</p>
</li>
<li><p><strong>可能要扩展到多机分布的用进程，多核分布用线程</strong></p>
</li>
<li><p><strong>都满足需求的情况下，用你最熟悉、最拿手的方式</strong></p>
</li>
</ol>
<p>总结：线程快而进程可靠性高</p>
<h2 id="cluster"><a href="#cluster" class="headerlink" title="cluster"></a>cluster</h2><blockquote>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/ShuiNian/p/15423317.html">理解Node.js中的”多线程”</a></p>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903740768518152">Node.js 真·多线程 Worker Threads 初探</a></p>
<p><a target="_blank" rel="noopener" href="http://nodejs.cn/api/cluster.html">Node API cluster 集群</a></p>
</blockquote>
<p><code>Worker Threads</code> 特性是在2018年6月20日的 v10.5.0 版本引入的</p>
<p>cluster 是 Node 进行多线程的模块</p>
<p><strong>CPU 数量查询</strong></p>
<ul>
<li>我的电脑 —— 管理 —— 设备管理器 —— 处理器</li>
</ul>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/js-img/cpu1.png"></p>
<ul>
<li><p>任务管理器 —— CPU —— 逻辑处理器</p>
<p>这里可以看到我的电脑有 4 个内核 8 个逻辑处理器，有多少个逻辑处理器，就可以开多少个线程</p>
</li>
</ul>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/js-img/cpu3.png"></p>
<h3 id="cluster-基本使用"><a href="#cluster-基本使用" class="headerlink" title="cluster 基本使用"></a>cluster 基本使用</h3><p>cluster 基本原理：主线程去 fork 子线程，然后管理它们</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> cluster = <span class="built_in">require</span>(<span class="string">&#x27;cluster&#x27;</span>) <span class="comment">// nodejs内置模块</span></span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> cpuNum = <span class="built_in">require</span>(<span class="string">&#x27;os&#x27;</span>).cpus().length</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> port = <span class="number">8000</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (cluster.isMaster) &#123;</span><br><span class="line">  <span class="comment">// 如果是主线程</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; cpuNum; i++) &#123;</span><br><span class="line">    cluster.fork() <span class="comment">// 开启子进程</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="comment">// 子线程走这个</span></span><br><span class="line">  http</span><br><span class="line">    .createServer(<span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">      res.writeHead(<span class="number">200</span>)</span><br><span class="line">      res.end(<span class="string">&#x27;hello world\r\n&#x27;</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    .listen(port, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">`running at: http://localhost:<span class="subst">$&#123;port&#125;</span>/`</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>多进程和单进程性能对比</strong></p>
<ul>
<li>多进程的性能要明显好于单进程</li>
</ul>
<p><strong>安装 Apache</strong></p>
<ul>
<li>安装 Apache 可以参考这篇文章：<a target="_blank" rel="noopener" href="https://www.skyfinder.cc/2020/08/14/windows10installapacheserver/">Windows 10 安装Apache</a></li>
<li>安装问题可能出现的问题：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/hahayixiao/p/11366148.html">通常每个套接字地址(协议/网络地址/端口)只允许使用一次::443</a></li>
<li>CMD 中使用 <code>netstat -a -o </code> 查看哪些端口被占用</li>
</ul>
<p>ab 是 apache 自带的压力测试工具，Mac 原生自带，无需安装</p>
<p><code>ab -n1000 -c50 127.0.0.1:8000/</code> </p>
<ul>
<li><code>-n</code> 请求数</li>
<li><code>-c</code> 并发数</li>
</ul>
<p><strong>Node 调试方法</strong></p>
<ul>
<li>可以手动选择运行和调试中的 <code>Launch Program</code></li>
<li>也可以在 <code>.vscode</code> 文件下面配置 <code>launch.json</code></li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="comment">// 使用 IntelliSense 了解相关属性。 </span></span><br><span class="line">    <span class="comment">// 悬停以查看现有属性的描述。</span></span><br><span class="line">    <span class="comment">// 欲了解更多信息，请访问: https://go.microsoft.com/fwlink/?linkid=830387</span></span><br><span class="line">    <span class="attr">&quot;version&quot;</span>: <span class="string">&quot;0.2.0&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;configurations&quot;</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="attr">&quot;type&quot;</span>: <span class="string">&quot;node&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;request&quot;</span>: <span class="string">&quot;launch&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;name&quot;</span>: <span class="string">&quot;Launch Program&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;program&quot;</span>: <span class="string">&quot;$&#123;workspaceFolder&#125;\\你运行的JS文件&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="process-进程"><a href="#process-进程" class="headerlink" title="process 进程"></a>process 进程</h3><ul>
<li>process 对象是 Node 的一个全局对象，提供当前 Node 进程的信息，它可以在脚本的任意位置使用，不必通过 require 命令加载</li>
</ul>
<p><strong>属性</strong></p>
<ol>
<li><strong>process.argv</strong> ：返回一个数组，包含了启动 node 进程的命令行参数</li>
<li><strong>process.env</strong> ：返回包含用户环境信息的对象，可以在脚本中对这个对象进行增删改查的操作</li>
<li><strong>process.pid</strong> ：返回当前进程的进程号</li>
<li><strong>process.platform</strong> ：返回当前的操作系统</li>
<li><strong>process.version</strong> ：返回当前 node 版本</li>
</ol>
<p><strong>方法</strong></p>
<ol>
<li><strong>process.cwd()</strong> ：返回 node.js 进程当前工作目录</li>
<li>process.chdir() ：变更 node.js 进程的工作目录</li>
<li><strong>process.nextTick(fn)</strong> ：将任务放到当前事件循环的尾部，添加到 “next tick” 队列，一旦当前事件轮询队列的任务全部完成，在 “next tick” 队列中的所有 callback 会被依次调用</li>
<li><strong>process.exit(）</strong> ：退出当前进程，很多时候是不需要的</li>
<li>process.kill(pid, [signal]) ：给指定进程发送信号，包括但不限于结束进程</li>
</ol>
<p><strong>事件</strong></p>
<ol>
<li><p>beforeExit 事件，在 Node 情况了 Event Loop 之后，再没有任何处理任务时触发，可以在这里部署一些任务，使得 Node 进程不退出，显示的终止程序时（<code>process.ext()</code>），不会触发</p>
</li>
<li><p>exit 事件，当前进程退出时触发，回调函数中只允许同步操作，因为执行完回调后，进程会退出</p>
</li>
<li><p><strong>uncaughtException</strong> 事件，当前进程抛出一个没有捕获的错误时触发，可以用它在进程结束前进行一些已分配资源的同步清理操作，尝试用它来恢复应用的正常运行的操作是不安全的</p>
<p>专门捕捉异步代码错误，比如在 http 请求中发生错误，就可以用 <code>process.on(&#39;uncaughtException&#39;, err =&gt; console.log(&#39;发生错误&#39;, err))</code> 进行兜底</p>
</li>
<li><p>warning 事件，任何 node.js 发出的进程警告，都会触发此事件</p>
</li>
</ol>
<h3 id="child-process"><a href="#child-process" class="headerlink" title="child_process"></a>child_process</h3><p>child_process 是 node.js 中用于创建子进程的模块，node 中大名鼎鼎的 cluster 是基于它来封装的</p>
<ol>
<li><p><strong>exec()</strong></p>
<p>异步衍生出一个 shell，然后在 shell 中执行命令，且缓冲任何产生的输出，运行结束后调用回调函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> exec = <span class="built_in">require</span>(<span class="string">&#x27;child_process&#x27;</span>).exec</span><br><span class="line"></span><br><span class="line"><span class="comment">// 回调方式</span></span><br><span class="line">exec(<span class="string">&#x27;ls&#x27;</span>, <span class="function">(<span class="params">err, stdout, stderr</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;stderr&#x27;</span>, stderr)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;stdout&#x27;</span>, stdout)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>由于标准输出和标准错误都是流对象（stream），可以监听 data 事件，因此上面的代码也可以写成下面这样</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123; exec &#125; = <span class="built_in">require</span>(<span class="string">&#x27;child_process&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 通过流的方式接受结果，类似文件读取</span></span><br><span class="line"><span class="keyword">const</span> child = exec(<span class="string">&#x27;ls&#x27;</span>)</span><br><span class="line">child.stdout.on(<span class="string">&#x27;data&#x27;</span>, <span class="function"><span class="params">data</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;stdout:&#x27;</span>, data)</span><br><span class="line">&#125;)</span><br><span class="line">child.stderr.on(<span class="string">&#x27;data&#x27;</span>, <span class="function"><span class="params">data</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;stderr:&#x27;</span>, data)</span><br><span class="line">&#125;)</span><br><span class="line">child.on(<span class="string">&#x27;close&#x27;</span>, <span class="function"><span class="params">code</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;closing code:&#x27;</span>, code)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>上面的代码还有一个好处。监听 data 事件以后，可以实时输出结果，否则只有等到子进程结束，才会输出结果。所以，如果子进程进行时间较长，或是持续运行，第二种写法更好</p>
</li>
<li><p><strong>execSync()</strong></p>
<p>exec() 的同步版本</p>
</li>
<li><p><strong>execFile()</strong></p>
<p>execFile 方法直接执行特定的程序 shell，参数作为数组传入， 不会被 bash 解释，因此具有较高的安全性</p>
<p>execFile 会自动过滤一些敏感字符串比如：<code>\</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123; execFile &#125; = <span class="built_in">require</span>(<span class="string">&#x27;child_process&#x27;</span>)</span><br><span class="line"></span><br><span class="line">execFile(<span class="string">&#x27;ls&#x27;</span>, [<span class="string">&#x27;-c&#x27;</span>], <span class="function">(<span class="params">error, stdout, stderr</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (error) <span class="built_in">console</span>.error(<span class="string">&#x27;error&#x27;</span>, error)</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;stdout&#x27;</span>, stdout)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>spawn()</strong></p>
<p>spawn 方法创建一个子进程来执行特定命令 shell，用法与 execFile 方法类似，但是没有回调函数，只能通过监听事件，来获取运行结果。它属于异步执行，适用于子进程长时间运行的情况</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123; spawn &#125; = <span class="built_in">require</span>(<span class="string">&#x27;child_process&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> child = spawn(<span class="string">&#x27;ls&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// data是Buffer</span></span><br><span class="line">child.stdout.on(<span class="string">&#x27;data&#x27;</span>, <span class="function"><span class="params">data</span> =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;data&#x27;</span>, data.toString()))</span><br><span class="line">child.on(<span class="string">&#x27;close&#x27;</span>, <span class="function"><span class="params">code</span> =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;code:&#x27;</span>, code))</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>fork()</strong></p>
<p>fork 方法直接创建一个子进程，执行 Node 脚本，<code>fork(&#39;./child.js&#39;)</code> 相当于 <code>spawn(&#39;node&#39;, [&#39;./child.js&#39;])</code>，与 spawn 方法不同的是，fork 会在父进程与子进程之间，建立一个通信管道 pipe，用于进程之间的通信，也是 IPC 通信的基础</p>
<p><code>main.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> child_process = <span class="built_in">require</span>(<span class="string">&#x27;child_process&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> child = child_process.fork(path.resolve(__dirname, <span class="string">&#x27;./son.js&#x27;</span>))</span><br><span class="line">child.on(<span class="string">&#x27;message&#x27;</span>, <span class="function"><span class="params">data</span> =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;father received:&#x27;</span>, data))</span><br><span class="line">child.send(<span class="string">&#x27;father send&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p><code>son.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">process.on(<span class="string">&#x27;message&#x27;</span>, <span class="function"><span class="params">data</span> =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;son received:&#x27;</span>, data))</span><br><span class="line">process.send(<span class="string">&#x27;hello father&#x27;</span>)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="cluster-属性和方法"><a href="#cluster-属性和方法" class="headerlink" title="cluster 属性和方法"></a>cluster 属性和方法</h3><ol>
<li><p><strong>isMaster</strong> 属性，返回该进程是不是主进程。v16.0.0 废弃改为 <strong>isPrimary</strong></p>
</li>
<li><p><strong>isWorker</strong> 属性，返回该进程是不是工作进程</p>
</li>
<li><p><strong>fork</strong> 方法，只能通过主进程调用，衍生出一个新的 worker 进程，返回一个 worker 对象</p>
<p>在 <code>cluster.fork()</code> 调用的时候，相当于执行了 <code>node main.js</code></p>
<p>和 <code>child_process</code> 的区别，不用创建一个新的 <code>child.js</code></p>
</li>
<li><p>setupMaster([settings]) 方法，用于修改 fork() 默认行为，一旦调用，将会按照 cluster.settings 进行设置。v16.0.0 废弃改为 setupPrimary</p>
</li>
<li><p>settings 属性，用于配置</p>
<p>exex: worker 文件路径</p>
<p>args: 传递给 worker 的参数</p>
<p>execArgv: 传递给 node.js 可执行文件的参数列表</p>
</li>
</ol>
<h3 id="cluster-事件"><a href="#cluster-事件" class="headerlink" title="cluster 事件"></a>cluster 事件</h3><ol>
<li><strong>fork</strong> 事件，当心的工作被 fork 时触发，可以用来记录工作进程活动，回调参数 worker 对象</li>
<li><strong>listening</strong> 事件，当一个工作进程调用 <code>listen()</code> 后触发，回调参数 worker 对象</li>
<li><strong>message</strong> 事件，比较特殊，需要去在单独 worker 上监听</li>
<li>online 事件，复制好一个工作进程后，工作进程主动发送一条 online 消息给主进程，主进程收到消息后触发，回调参数 worker 对象</li>
<li><strong>disconnect</strong> 事件，主进程和工作进程之间 IPC 通道断开后触发</li>
<li><strong>exit</strong> 事件，有工作进程退出时触发，回调参数：worker 对象、code 退出码、signal 进程被 kill 时的信号</li>
<li>setup 事件，<code>cluster.setupMaster()</code> 执行后触发</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> cluster = <span class="built_in">require</span>(<span class="string">&#x27;cluster&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> cpuNum = <span class="built_in">require</span>(<span class="string">&#x27;os&#x27;</span>).cpus().length</span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> port = <span class="number">8001</span></span><br><span class="line"><span class="keyword">if</span> (cluster.isMaster) &#123;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; cpuNum; i++) &#123;</span><br><span class="line">    cluster.fork()</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  cluster.on(<span class="string">&#x27;fork&#x27;</span>, <span class="function"><span class="params">worker</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;主进程 fork 了一个 worker pid 为：&#x27;</span>, worker.process.pid)</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  cluster.on(<span class="string">&#x27;listening&#x27;</span>, <span class="function"><span class="params">worker</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;worker &#x27;</span> + worker.process.pid + <span class="string">&#x27; died&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  <span class="built_in">Object</span>.keys(cluster.workers).forEach(<span class="function"><span class="params">id</span> =&gt;</span> &#123;</span><br><span class="line">    cluster.workers[id].on(<span class="string">&#x27;message&#x27;</span>, <span class="function"><span class="params">data</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&#x27;接收data&#x27;</span>, data)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 需要结合任务管理器把对应pid的任务结束</span></span><br><span class="line">  cluster.on(<span class="string">&#x27;disconnect&#x27;</span>, <span class="function"><span class="params">worker</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;有工作进程退出了&#x27;</span>, worker.process.pid)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="comment">// 对应cluster.on(&#x27;listening&#x27;)</span></span><br><span class="line">  http</span><br><span class="line">    .createServer(<span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">      res.writeHead(<span class="number">200</span>)</span><br><span class="line">      res.end(<span class="string">&#x27;hello world\r\n&#x27;</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    .listen(port, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">`running at: http://localhost:<span class="subst">$&#123;port&#125;</span>/`</span>)</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 对应cluster.on(&#x27;message&#x27;)</span></span><br><span class="line">  process.send(<span class="string">&#x27;hello&#x27;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="cluster-多线程模型"><a href="#cluster-多线程模型" class="headerlink" title="cluster 多线程模型"></a>cluster 多线程模型</h3><blockquote>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/qingmingsang/articles/8278128.html">cluster 惊群</a></p>
</blockquote>
<p>每个 worker 进程通过使用 <code>child_process.fork()</code> 函数，基于 IPC（Inter-Process Communication，进程间通信），实现与 master 进程间通信</p>
<p>那我们直接用 <code>child_process.fork()</code> 实现不就行了，为什么还要用 cluster？</p>
<ul>
<li><code>child_process.fork()</code> 这样方式仅仅实现了多进程。多进程运行还涉及父子进程通信，子进程管理，以及负载均衡等问题，这些特性 cluster 帮你实现了</li>
</ul>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/js-img/clusterWorker.png"></p>
<p><strong>最初的多进程模型</strong></p>
<p>最初的 node.js 多进程模型是这样实现的，master 进程创建 socket，绑定到某个地址以及端口后，自身不调用 listen 来监听连接以及 accept 连接，而是将该 socket 的 fd 传递到 fork 出来的 worker 进程，worker 接收到 fd 后再调用 listen，accept 新的连接。但实际一个新到来的连接最终只能被某一个 worker 进程 accept 再做处理，至于是哪个 worker 能够 accept 到，开发者完全无法预知以及干预。这势必就导致了当一个新连接到来时，多个 worker 进程会产生竞争，最终由胜出的 worker 获取连接</p>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/js-img/%E6%83%8A%E7%BE%A4%E7%8E%B0%E8%B1%A1.png"></p>
<ul>
<li>多个进程之间会竞争 accept 一个连接，产生惊群现象，效率比较低（4 个 worker 去抢请求）</li>
<li>由于无法控制一个新的连接由哪个进程来处理，必然导致各 worker 进程之间的负载非常不均衡</li>
</ul>
<p>简单说来，多线程/多进程等待同一个 socket 事件，当这个事件发生时，这些线程/进程被同时唤醒，就是惊群</p>
<p>惊群通常发生在 server 上，当父进程绑定一个端口监听 socket，然后 fork 出多个子进程，子进程们开始循环处理（比如 accept）这个 socket。每当用户发起一个 TCP 连接时，多个子进程同时被唤醒，然后其中一个子进程 accept 新连接成功，余者皆失败，重新休眠</p>
<p><code>main.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> net = <span class="built_in">require</span>(<span class="string">&#x27;net&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> &#123; fork &#125; = <span class="built_in">require</span>(<span class="string">&#x27;child_process&#x27;</span>) <span class="comment">// 惊群</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> handle = net._createServerHandle(<span class="string">&#x27;0.0.0.0&#x27;</span>, <span class="number">3005</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;fork&#x27;</span>, i)</span><br><span class="line">  fork(<span class="string">&#x27;./worker.js&#x27;</span>).send(&#123;&#125;, handle)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>worker.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> net = <span class="built_in">require</span>(<span class="string">&#x27;net&#x27;</span>)</span><br><span class="line"></span><br><span class="line">process.on(<span class="string">&#x27;message&#x27;</span>, <span class="function">(<span class="params">m, handle</span>) =&gt;</span> &#123;</span><br><span class="line">  start(handle)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> buf = <span class="string">&#x27;hello nodejs&#x27;</span></span><br><span class="line"><span class="keyword">const</span> res = [<span class="string">&#x27;HTTP/1.1 200 OK&#x27;</span>, <span class="string">&#x27;content-length:&#x27;</span> + buf.length].join(<span class="string">&#x27;\r\n&#x27;</span>) + <span class="string">&#x27;\r\n\r\n&#x27;</span> + buf</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> data = &#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">start</span>(<span class="params">server</span>) </span>&#123;</span><br><span class="line">  server.listen()</span><br><span class="line">  server.onconnection = <span class="function">(<span class="params">err, handle</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> pid = process.pid</span><br><span class="line">    <span class="keyword">if</span> (!data[pid]) data[pid] = <span class="number">0</span></span><br><span class="line">    data[pid]++ <span class="comment">// 每次服务+1</span></span><br><span class="line">    <span class="comment">// 最后出现抢请求现象，导致data[pid]，每个处理次数不一样</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;got a connection on worker, pid = %d&#x27;</span>, process.pid, data[pid])</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> socket = <span class="keyword">new</span> net.Socket(&#123;</span><br><span class="line">      handle: handle,</span><br><span class="line">    &#125;)</span><br><span class="line">    socket.readable = socket.writable = <span class="literal">true</span></span><br><span class="line">    socket.end(res)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Nginx-多线程模型"><a href="#Nginx-多线程模型" class="headerlink" title="Nginx 多线程模型"></a>Nginx 多线程模型</h3><p>Nginx 是俄罗斯人编写的十分轻量级的 HTTP 服务器，Nginx，它的发音为 “engine X”，是一个高性能 HTTP 和反向代理服务器。异步非阻塞 I/O，而且能够高并发</p>
<ul>
<li>正向代理：客户端为代理，服务器不知道客户端是谁</li>
<li>反向代理：服务器为代理。客户端不知道服务器是谁</li>
</ul>
<p>Nginx 配置 demo：</p>
<ul>
<li>一个端口挂掉整个都挂掉，且没有重启机制</li>
</ul>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">http</span> &#123;</span><br><span class="line">    <span class="attribute">upstream</span> cluster &#123;</span><br><span class="line">        server: 127.0.0.1:3000;</span><br><span class="line">        server: 127.0.0.1:3001;</span><br><span class="line">        server: 127.0.0.1:3002;</span><br><span class="line">        server: 127.0.0.1:3003;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="section">server</span> &#123;</span><br><span class="line">        listen: 80</span><br><span class="line">        <span class="attribute">server_name</span> www.domain.com</span><br><span class="line">        location / &#123;</span><br><span class="line">            <span class="attribute">proxy_pass</span> http://cluster</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Nginx 的实际应用场景：比较适合稳定的服务</p>
<ul>
<li>静态资源服务器 html、css、js</li>
<li>企业级集群</li>
</ul>
<blockquote>
<p>守护进程：退出命令行窗口之后，服务一直处于运行状态</p>
</blockquote>
<h3 id="cluster-多线程调度模型"><a href="#cluster-多线程调度模型" class="headerlink" title="cluster 多线程调度模型"></a>cluster 多线程调度模型</h3><blockquote>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/qingmingsang/articles/8278128.html">cluster 负载均衡</a></p>
</blockquote>
<p>cluster 是由 master 监听请求，再通过 <code>round-robin</code> 算法分发给各个 worker，避免惊群现象发生</p>
<ul>
<li><code>round-robin</code> <strong>轮询调度算法</strong> 原理是每一次把来自用户的请求轮流给内部的服务器</li>
</ul>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/js-img/cluster%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1.png"></p>
<p><code>main.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> net = <span class="built_in">require</span>(<span class="string">&#x27;net&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> &#123; fork &#125; = <span class="built_in">require</span>(<span class="string">&#x27;child_process&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// cluster简易版本，cluster就是基于child_process进行封装的</span></span><br><span class="line"><span class="keyword">let</span> workers = []</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) &#123;</span><br><span class="line">  workers.push(fork(<span class="string">&#x27;./worker.js&#x27;</span>)) <span class="comment">// cluster workers</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> handle = net._createServerHandle(<span class="string">&#x27;0.0.0.0&#x27;</span>, <span class="number">3005</span>)</span><br><span class="line">handle.listen()</span><br><span class="line">handle.onconnection = <span class="function">(<span class="params">err, handle</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> worker = workers.pop()</span><br><span class="line">  worker.send(&#123;&#125;, handle)</span><br><span class="line">  <span class="comment">// 通过pop和unshift实现一个简易版的轮询</span></span><br><span class="line">  workers.unshift(worker)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>worker.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> net = <span class="built_in">require</span>(<span class="string">&#x27;net&#x27;</span>)</span><br><span class="line"></span><br><span class="line">process.on(<span class="string">&#x27;message&#x27;</span>, <span class="function">(<span class="params">m, handle</span>) =&gt;</span> &#123;</span><br><span class="line">  start(handle)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> buf = <span class="string">&#x27;hello nodejs&#x27;</span></span><br><span class="line"><span class="keyword">const</span> res = [<span class="string">&#x27;HTTP/1.1 200 OK&#x27;</span>, <span class="string">&#x27;content-length:&#x27;</span> + buf.length].join(<span class="string">&#x27;\r\n&#x27;</span>) + <span class="string">&#x27;\r\n\r\n&#x27;</span> + buf</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">start</span>(<span class="params">server</span>) </span>&#123;</span><br><span class="line">  server.listen()</span><br><span class="line">  server.onconnection = <span class="function">(<span class="params">err, handle</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;got a connection on worker, pid = %d&#x27;</span>, data[pid])</span><br><span class="line">    <span class="keyword">const</span> socket = <span class="keyword">new</span> net.Socket(&#123;</span><br><span class="line">      handle: handle,</span><br><span class="line">    &#125;)</span><br><span class="line">    socket.readable = socket.writable = <span class="literal">true</span></span><br><span class="line">    socket.end(res)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="cluster-优雅退出和进程守护"><a href="#cluster-优雅退出和进程守护" class="headerlink" title="cluster 优雅退出和进程守护"></a>cluster 优雅退出和进程守护</h3><p><strong>cluster 中的优雅退出</strong></p>
<ol>
<li>关闭异常 Worker 进程所有的 TCP Server（将已有的连接快速断开，且不再接收新的连接），断开和 Master 的 IPC 通道，不再接受新的用户请求</li>
<li>Master 立刻 fork 一个新的 Worker 进程，保证在线 【工人】总数不变</li>
<li>异常 Worker 等待一段时间，处理完已经接受的请求后退出</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (cluster.isMaster) &#123;</span><br><span class="line">  cluster.fork()</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">  &#125; <span class="keyword">catch</span> &#123;</span><br><span class="line">    process.disconnect()</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>进程守护</strong></p>
<p>Master 进程除了负责接收新的连接，分发给各 worker 进程处理之外，还得像天使一样默默地守护者这些 worker 进程，保障整个应用的稳定性。一旦某个 worker 进程异常退出就 fork 一个新的子进程顶替上去</p>
<p>这一切 cluster 模块都已经处理好了，当某个 worker 进程发生异常退出或者与 Master 进程失去联系（disconnected）时，Master 进程都会收到相应的事件通知</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">cluster.on(<span class="string">&#x27;exit&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  cluster.fork()</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">cluster.on(<span class="string">&#x27;disconnect&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  cluster.fork()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="IPC-通信"><a href="#IPC-通信" class="headerlink" title="IPC 通信"></a>IPC 通信</h3><p>IPC（Inter-Process Communication，进程间的通信）</p>
<p>虽然每个 Worker 进程是相互对立的，但是它们之间始终还是需要通讯的，叫进程间通讯（IPC）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> cluster = <span class="built_in">require</span>(<span class="string">&#x27;cluster&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (cluster.isMaster) &#123;</span><br><span class="line">  <span class="keyword">const</span> worker = cluster.fork()</span><br><span class="line">  worker.send(<span class="string">&#x27;hi there&#x27;</span>)</span><br><span class="line">  worker.on(<span class="string">&#x27;message&#x27;</span>, <span class="function"><span class="params">msg</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`msg: <span class="subst">$&#123;msg&#125;</span> from worker#<span class="subst">$&#123;worker.id&#125;</span>`</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (cluster.isWorker) &#123;</span><br><span class="line">  process.on(<span class="string">&#x27;message&#x27;</span>, <span class="function"><span class="params">msg</span> =&gt;</span> &#123;</span><br><span class="line">    process.send(msg)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>cluster 的 IPC 通道只存在于 Master 和 Worker 之间，Worker 与 Worker 进程互相间是没有的。Worker 之间通讯该怎么办？通过 Master 来转发</p>
<p>核心：worker 直接的通信，靠 master 转发，利用 worker 的 pid</p>

    </div>

    
    
    

	<div>
		  
			
<div class="my_post_copyright clearfix">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <article class="box-left">
    <img src="https://gitee.com/lilyn/pic/raw/master/logo.jpg">
  </article>
  <article class="box-right">
    <p><span>本文标题:</span><a href="/posts/126e4b0f/">Node 事件循环及多线程</a></p>
    <p><span>文章作者:</span><a href="/" title="访问 LiLyn 的个人博客">LiLyn</a></p>
    <p><span>原始链接:</span><a href="/posts/126e4b0f/" title="Node 事件循环及多线程">http://llmysnow.top/posts/126e4b0f/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://llmysnow.top/posts/126e4b0f/"  aria-label="复制成功！"></i></span>
  </p>
    <p><span>许可协议:</span>转载请保留原文链接及作者。</p>  
  </article>
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

		  
	</div>

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Node/" rel="tag"><i class="fa fa-tag"></i> Node</a>
              <a href="/tags/%E6%B5%8F%E8%A7%88%E5%99%A8/" rel="tag"><i class="fa fa-tag"></i> 浏览器</a>
              <a href="/tags/%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF/" rel="tag"><i class="fa fa-tag"></i> 事件循环</a>
              <a href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag"><i class="fa fa-tag"></i> 多线程</a>
          </div>
		 
		<!--post-tags 彩色标签-->
		<script type="text/javascript">
		var tagsall=document.getElementsByClassName("post-tags")
		for (var i = tagsall.length - 1; i >= 0; i--){
			var tags=tagsall[i].getElementsByTagName("a");
			for (var j = tags.length - 1; j >= 0; j--) {
				var r=Math.floor(Math.random()*75+130);
				var g=Math.floor(Math.random()*75+100);
				var b=Math.floor(Math.random()*75+80);
				tags[j].style.background = "rgb("+r+","+g+","+b+")";
				tags[j].style.color = "#fff";
				tags[j].style.padding = "0 10px";
			}
		}                        
		</script>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/e8c036a5/" rel="prev" title="实现JS一些重要的API">
      <i class="fa fa-chevron-left"></i> 实现JS一些重要的API
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/735a614e/" rel="next" title="VScode 前端常用配置/设置/问题">
      VScode 前端常用配置/设置/问题 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF"><span class="nav-text">浏览器事件循环</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Node-js-%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF"><span class="nav-text">Node.js 事件循环</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E5%85%AD%E4%B8%AA%E9%98%B6%E6%AE%B5"><span class="nav-text">事件循环六个阶段</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#fs-%E5%92%8C-setTimeout-%E7%9A%84%E5%85%B3%E7%B3%BB"><span class="nav-text">fs 和 setTimeout 的关系</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#setTimeout-%E5%92%8C-setImmediate"><span class="nav-text">setTimeout 和 setImmediate</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#process-nextTick"><span class="nav-text">process.nextTick</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#nextTick-%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text">nextTick 应用场景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Node-%E5%A4%9A%E7%BA%BF%E7%A8%8B"><span class="nav-text">Node 多线程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%9A%E8%BF%9B%E7%A8%8B%E5%92%8C%E5%A4%9A%E7%BA%BF%E7%A8%8B"><span class="nav-text">多进程和多线程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E9%80%89%E9%80%89%E6%8B%A9%E5%A4%9A%E8%BF%9B%E7%A8%8B%E8%BF%98%E6%98%AF%E5%A4%9A%E7%BA%BF%E7%A8%8B"><span class="nav-text">如何选选择多进程还是多线程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#cluster"><span class="nav-text">cluster</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#cluster-%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="nav-text">cluster 基本使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#process-%E8%BF%9B%E7%A8%8B"><span class="nav-text">process 进程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#child-process"><span class="nav-text">child_process</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cluster-%E5%B1%9E%E6%80%A7%E5%92%8C%E6%96%B9%E6%B3%95"><span class="nav-text">cluster 属性和方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cluster-%E4%BA%8B%E4%BB%B6"><span class="nav-text">cluster 事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cluster-%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%A8%A1%E5%9E%8B"><span class="nav-text">cluster 多线程模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Nginx-%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%A8%A1%E5%9E%8B"><span class="nav-text">Nginx 多线程模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cluster-%E5%A4%9A%E7%BA%BF%E7%A8%8B%E8%B0%83%E5%BA%A6%E6%A8%A1%E5%9E%8B"><span class="nav-text">cluster 多线程调度模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cluster-%E4%BC%98%E9%9B%85%E9%80%80%E5%87%BA%E5%92%8C%E8%BF%9B%E7%A8%8B%E5%AE%88%E6%8A%A4"><span class="nav-text">cluster 优雅退出和进程守护</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IPC-%E9%80%9A%E4%BF%A1"><span class="nav-text">IPC 通信</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="LiLyn"
      src="/images/logo.jpg">
  <p class="site-author-name" itemprop="name">LiLyn</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">70</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">162</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/llwodexue" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;llwodexue" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/qq_38689395" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_38689395" rel="noopener" target="_blank"><i class="fas fa-copyright fa-fw"></i>CSDN</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://scx69.gitee.io/blogs/" title="https:&#x2F;&#x2F;scx69.gitee.io&#x2F;blogs&#x2F;" rel="noopener" target="_blank">花开满城</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://yixin-oss.gitee.io/daytoy/" title="http:&#x2F;&#x2F;yixin-oss.gitee.io&#x2F;daytoy&#x2F;" rel="noopener" target="_blank">daytoy</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LiLyn</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">463k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">7:01</span>
</div>

<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>-->

<!--
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>-->

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  

  <!-- 动态线条背景 -->
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  <!-- 页面点击小红心 -->
  <script type="text/javascript">
	!function(e,t,a){function n(){c(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"),o(),r()}function r(){for(var e=0;e<d.length;e++)d[e].alpha<=0?(t.body.removeChild(d[e].el),d.splice(e,1)):(d[e].y--,d[e].scale+=.004,d[e].alpha-=.013,d[e].el.style.cssText="left:"+d[e].x+"px;top:"+d[e].y+"px;opacity:"+d[e].alpha+";transform:scale("+d[e].scale+","+d[e].scale+") rotate(45deg);background:"+d[e].color+";z-index:99999");requestAnimationFrame(r)}function o(){var t="function"==typeof e.onclick&&e.onclick;e.onclick=function(e){t&&t(),i(e)}}function i(e){var a=t.createElement("div");a.className="heart",d.push({el:a,x:e.clientX-5,y:e.clientY-5,scale:1,alpha:1,color:s()}),t.body.appendChild(a)}function c(e){var a=t.createElement("style");a.type="text/css";try{a.appendChild(t.createTextNode(e))}catch(t){a.styleSheet.cssText=e}t.getElementsByTagName("head")[0].appendChild(a)}function s(){return"rgb("+~~(255*Math.random())+","+~~(255*Math.random())+","+~~(255*Math.random())+")"}var d=[];e.requestAnimationFrame=function(){return e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)}}(),n()}(window,document);
  </script>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body>
</html>